// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------

import crypto from 'crypto'
import BaseBusinessController from './../base/BaseBusinessController'

class AccountController extends BaseBusinessController {
    /**
     * 查看Token中的用户信息
     * @returns {*}
     */
    async actionMy() {
        console.log("查看大户素", this.state.user)
        return this.state.user;
    }


    /**
     * 查看个人用户信息
     * 支持账户查询
     * @returns {Promise<*>}
     */
    async actionView(){
        let id = $_POST['id'] ? $_POST['id']: this.state.user.id

        let info = await this.modules("Account").where({id}).first();
        delete info['password'];

        if(info.role_id){
            info['role'] = await this.modules('Role').where({id: info.role_id}).first()
        }

        let pr = await super._findAccountPermissions(id)
        let permissionList = []
        for(let p of pr){
            permissionList.push(p.code)
        }

        info['permissions'] = permissionList

        return info;
    }


    /**
     * 更新用户信息
     * @returns {Promise<*>}
     */
    async actionUpdate(){
        let id = $_POST['id'] ? $_POST['id']: this.state.user.id

        let {
            user_name,
            real_name,
            mobile,
            id_card,
            is_disable,
            password,
            role_id
        } = $_POST

        let data = {
            user_name,
            real_name,
            mobile,
            id_card,
            is_disable,
            role_id
        }

        if(password){
            data['password'] = this.getPassword(password);
        }

        return await this.modules("Account").where({id}).update(data);
    }

    async actionUpdatePassword(){
        if (!$_POST['password']) {
            throw new Error('密码不能为空');
        }
        let oldPassword = this.getPassword($_POST['old_password']);
        let info = await this.modules("Account").where({"id": this.state.user.id}).first();
        if (oldPassword == info['password']) {
            let password = this.getPassword($_POST['password']);
            return await this.modules("Account").where({"id": this.state.user.id}).update({password});
        } else {
            throw new Error('旧密码不正确');
        }
    }


    /**
     * 获取用户列表
     * @returns {Promise.<void>}
     */
    async actionFindAll(){
        let {number, size} = super._getPage();
        let {real_name, mobile, app_id} = $_POST
        if(!app_id){
            throw new Error("端参数缺失");
        }
        let whereOption = {app_id}
        if(real_name){
            whereOption['real_name'] = {
                [Op.like]: `%${real_name}%`
            }
        }
        if(mobile){
            whereOption['mobile'] = {
                [Op.like]: `%${mobile}%`
            }
        }
        let listResult = await this.modules("Account").where(whereOption).page(number, size).joinWith(['Role']).select(false, {raw: true});

        let {children} = listResult
        for(let ac of children){
            let sql = "SELECT GROUP_CONCAT(b.`name`) as builds FROM hz_account_building rb LEFT JOIN hz_building b ON b.id = rb.building_id WHERE rb.account_id = :accoundId"
            let result = await db.sql(sql, {accoundId: ac.role_id})
            ac.builds = result[0].builds
        }
        let userRole=await super._findRoleByUser(this.state)
        //console.log(userRole)
        listResult.children=children.filter(p=>{
             return p['role.level']>=userRole.level
            })
        return listResult;
    }


    /**
     * 启用、停止账号
     * @returns {Promise.<void>}
     */
    async actionDisable(){
        let {id, is_disable} = $_POST
        if(!id){
            throw  new Error("参数缺失")
        }
        await super._findAccount(id)
        return await this.modules("Account").where({id}).update({is_disable})
    }

    /**
     * 创建数据
     * @return {[type]} [description]
     */
    async actionAdd() {
        if(!this.isAdmin(this.state)){
            throw new Error("不是管理员，创建失败");
        }

        let {user_name, real_name, password, id_card, role_id, app_id} = $_POST
        if(!app_id){
            throw new Error("端参数缺失");
        }
        if(!user_name){
            throw new Error("用户名不能为空");
        }
        if(!real_name){
            throw new Error("真实姓名不能为空");
        }
        if(!password){
            throw new Error("密码不能为空");
        }
        if(!id_card){
            throw new Error("身份证不能为空");
        }
        if(!role_id){
            throw new Error("角色ID不能为空");
        }

        let userInfo = await this.modules("Account").where({"user_name": $_POST['user_name']}).first();
        if (userInfo && userInfo.mobile) {
            throw new Error('该账号已存在');
        } else {
            $_POST['password'] = this.getPassword($_POST['password']);
            $_POST['is_admin'] = 0
            $_POST['is_disable'] = 0
            return this.modules("Account").insert($_POST);
        }
    }

    /**
     * 设置登陆密码
     * @param  {[type]} str [description]
     * @return {[type]}     [description]
     */
    getPassword(str) {
        if (!str) {
            return '';
        }
        let key = 'W4xOLXEvo*$8pk%aruoV!&t$5NAp0HHl';
        let obj = crypto.createHash('md5');
        obj.update(str + key);
        return obj.digest('hex');
    }

    /**
     * 删除用户
     * @returns {Promise<boolean>}
     */
    async actionRemove(){
        if(!this.isAdmin(this.state)){
            throw new Error("不是管理员，删除失败");
        }

        let id = $_POST['id']
        if(!id){
            throw  new Error("参数缺失")
        }

        await super._validateAccount(id)

        if(await this.isAdminAccount(id)){
            throw new Error("系统管理员，不可删除");
        }

        let res = await this.modules('Account').where({ id }).destroy();
        if (res) {
            return true;
        } else {
            throw new Error('删除失败');
        }

    }

    /**
     * 获取列表信息
     * @return {[type]} [description]
     */
    actionCompany() {
        return new Promise((resolve, reject) => {
            if ($_GET["page[size]"] && $_GET["page[number]"]) {
                let size = $_GET["page[size]"];
                let number = $_GET["page[number]"];
                this.modules('Account').order(['id', 'DESC']).where({role: 'company'}).joinWith(['Company']).page(number, size).select().then(data => {
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            } else {
                this.modules(this.__ModelName__).order(['id', 'DESC']).select().then(data => {
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            }
        })
    }



    /**
     * 查询
     * @return {[type]} [description]
     */
    async actionBuildings() {
        let id = $_POST['id'];
        await super._validateAccount(id);

        let sql = "select b.* from hz_account_building rb INNER JOIN hz_building b ON b.id = rb.building_id WHERE rb.account_id = :account_id";
        return await db.sql(sql, {account_id: id})
    }


    /**
     * 修改
     * @return {[type]} [description]
     */
    async actionUpdateBuildings() {
        let id = $_POST['id'];
        let role = await this.modules('Account').where({ id }).first();
        if (!role) {
            throw new Error('用户不存在');
        }

        let t = await db.transaction();
        try{
            let buildingIds = $_POST['building_ids'];
            await this.modules('Account.AccountBuilding').where({ role_id: id }).destroy({transaction: t});

            let result = []
            for(let building_id of buildingIds){
                result.push({
                    building_id,
                    account_id: id
                })
            }
            await this.modules('Account.AccountBuilding').bulkCreate(result, {transaction: t})

            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("修改失败");
        }
    }

    /**
     * 获取本人所负责的楼宇ID
     * @returns {Promise.<void>}
     */
    async actionMyBuildingIds(){
        super.isValidAccount(this.state)
        return await super._getBuildingIdsByAccountId(this.state.user.id);
    }


    /**
     * 管理员绑定小程序
     * @returns {Promise<void>}
     */
    async actionBindWeApp(){
        let {open_id, code, account_id} = $_POST
        if(!account_id){
            throw new Error("参数缺失")
        }
        if(!(open_id || code)){
            throw new Error("参数缺失")
        }

        let account = await super._findAccount(account_id)
        if(account.open_id){
            throw new Error("您已绑定微信");
        }

        if (code) {
            let $Weapp = wechat.get_instance("weapp", {
                appid: global.APP_ID,
                appsecret: global.APP_SECRET
            });

            let result = await $Weapp.weappLogin(data.code);
            if (!result) {
                throw new Error('登录失败');
            }

            open_id = result.openid
        }

        let waccount = await this.modules('Account').where({open_id}).first()
        if(waccount){
            throw new Error("该微信已绑定其他账户");
        }

        return await this.modules('Account').where({id:account_id}).update({open_id});
    }

}

export default AccountController;
